# encoding: UTF-8
'''
Created: 2014-05-28 16:32

@author: VAN
'''
from _codecs import encode
import json
import urllib2

from comm.util import jsonp, htmlunescape
from orm.crawler import QQCategory


def categorys():
    categorys_json_url = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_diss_tag_conf.fcg?g_tk=1892417234&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
    
    req = urllib2.Request(url=categorys_json_url)
    html = urllib2.urlopen(req).read()
    
    html = htmlunescape(html)
    
    json_obj = jsonp(html)
    
    if len(json_obj) > 0:
        data = json_obj['data']['categories']
        
        for obj in data:
            c_g_name = obj['categoryGroupName']
            items = obj['items']
            for item in items:
                item_id = item['categoryId']
                item_name = item['categoryName']
                sorts = item['allsorts']
                
                entity = QQCategory()
                entity.id = item_id
                entity.name = item_name
                entity.g_name = c_g_name
                
                entity.exts = json.dumps(sorts).encode("utf-8");
                
                entity.save()
                
# categorys()
                
def category_item():
    categorys = QQCategory.objects.all()
    
    category_item_json_url = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_diss_by_tag.fcg?categoryId={cid}&sortId={sid}&sin=0&ein=19&format=jsonp&g_tk=1892417234&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
             
    for item in categorys:
        json_exts = json.loads(item.exts)
        for sort in json_exts:
            url = category_item_json_url.format(cid=item.id, sid=sort.id)
            req = urllib2.Request(url=url)
            html = urllib2.urlopen(req).read()
 
            json_obj = jsonp(html)
            
def handle_item():
    item = QQCategory()
    item.id = '143'
    item.name = 'abc'
    item.exts = u'[{"sortId": 2, "sortName": "\u6700\u65b0"}, {"sortId": 3, "sortName": "\u6700\u70ed"}, {"sortId": 4, "sortName": "\u8bc4\u5206"}]'
#     category_item_json_url = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_diss_by_tag.fcg?categoryId={cid}&sortId={sid}&sin=0&ein=19&format=jsonp&g_tk=1892417234&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
#     json_exts = json.loads(item.exts)
#     for sort in json_exts:
#         url = category_item_json_url.format(cid=item.id, sid=sort['sortId'])
#         req = urllib2.Request(url=url)
#         html = urllib2.urlopen(req).read()
#         print html
    item.items()
    
        
handle_item()

            
        
